(function($) {
	var groupCode = '',
		groupDesc = '',
		locId = '',
		locDesc = '';
	var schArr = [];
	var absArr = [];
	$.init({
		swipeBack: true //启用右滑关闭功能
	});
	$.plusReady(function() {
		var currentLoc = getLocalData('currentLoc');
		if(currentLoc) {
			groupCode = currentLoc['GroupCode'];
			groupDesc = currentLoc['GroupDesc'];
			locId = currentLoc['LocId'];
			locDesc = currentLoc['LocDesc'];
		} else {
			mui.toast('用户未登录');
			mui.openWindow('logon-shell.html', 'logon-shell');
			return;
		}
		mui('.mui-scroll-wrapper').scroll();
		var liDate = document.getElementById('li-date');
		if (plus.os.name == 'iOS') {
			liDate.addEventListener('tap', iosDateShow, false);
		}else{
			liDate.addEventListener('tap', function() {
				liDateClicked('li-date', 'date');
			}, false);
		}
		var liSchCode = document.getElementById('li-schCode');
		liSchCode.addEventListener('tap', liSchCodeClicked, false);

		var submitBtn = document.getElementById('submitBtn');
		submitBtn.addEventListener('tap', submitBtnClicked, false);
		getSchCodeData();
		getAbsentCodeData();
	});
	jQuery("#textarea").on("input propertychange", function() {
		var $this = jQuery(this),
			_val = $this.val(),
			count = "";
		if(_val.length > 100) {
			$this.val(_val.substring(0, 100));
			mui.toast('最多输入100个字符')
		}
		count = $this.val().length;
		jQuery("#text-count").text(count);
	});

	function liDateClicked(liId, spanId) {
		var textareaE = document.getElementById('textarea');
		textareaE.blur();
		var li = document.getElementById(liId);
		var _self = li;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				var spanele = document.getElementById(spanId);
				spanele.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
			});
		} else {
			var optionsJson = '{"type":"date"}';
			var options = JSON.parse(optionsJson);
			_self.picker = new mui.DtPicker(options);
			_self.picker.show(function(rs) {
				var spanele = document.getElementById(spanId);
				spanele.innerText = rs.text;
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	
	function iosDateShow(){
		var textareaE = document.getElementById('textarea');
		textareaE.blur();
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var dateStr = d.getFullYear()+'-'
			if (d.getMonth() < 9) {
				dateStr += '0'
			}
			dateStr += (d.getMonth() + 1)+'-'
			if (d.getDate() < 10) {
				dateStr += '0'
			}
			dateStr += d.getDate()
			var spanele = document.getElementById('date');
			spanele.innerText = dateStr
		}, function(e) {
			
		}, {});
	}

	function liSchCodeClicked() {
		var textareaE = document.getElementById('textarea');
		textareaE.blur();
		if(schArr.length == 0) {
			plus.nativeUI.showWaiting('获取排班代码');
			getSchCodeData(true);
		} else if(absArr.length == 0) {
			plus.nativeUI.showWaiting('获取排班代码');
			getAbsentCodeData(true);
		} else {
			mui('#selCodePopo').popover('toggle');
		}
	}

	function getSchCodeData(show) {
		var xmlStr = '<Request>' + locId + '</Request>';
		var methodStr = 'nurse.schedule.postdata';
		postHttpRequest(xmlStr, methodStr, function(result) {
			// console.log(result);
			if(result) {
				schArr = eval('(' + result + ')');
				updateCodeAreaUI(schArr, 'schArea', show);
			} else {
				mui.toast("未能获取到排班岗位数据（result为空）");
				plus.nativeUI.closeWaiting();
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}

	function getAbsentCodeData(show) {
		var xmlStr = '<Request>N</Request>';
		postHttpRequest(xmlStr, 'nurse.personal.holiday', function(result) {
			if(result) {
				absArr = eval('(' + result + ')');
				updateCodeAreaUI(absArr, 'absArea', show);
			} else {
				mui.toast("未能获取到排班岗位数据（result为空）");
			}
			plus.nativeUI.closeWaiting();
			if(show) {
				mui('#selCodePopo').popover('toggle');
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}

	function updateCodeAreaUI(dataArr, idStr, show) {
		var currentWidth = screen.width;
		var codeCount = dataArr.length;
		var oneLineCount = 7;
		var cellWidth = (currentWidth - (oneLineCount + 1) * 10) / oneLineCount;
		var lineCount = parseInt(codeCount / oneLineCount);
		var yuCount = codeCount % oneLineCount;
		if(yuCount != 0) {
			lineCount += 1;
		}
		var areaHtml = '';
		var keyStr = 'HolidayDesc';
		if(idStr == 'schArea') {
			keyStr = 'PostDesc';
		}
		for(var i = 0; i < lineCount; i++) {
			var count = oneLineCount;
			if(yuCount != 0 && i == lineCount - 1) {
				count = yuCount;
			}
			var trHtml = '<tr>';
			for(var j = 0; j < count; j++) {
				var index = i * oneLineCount + j;
				var codeStr = '';
				var codeIndex = 0;
				var idIndex = index;
				oneData = dataArr[index];
				var codeStr = oneData[keyStr];
				while(codeStr.indexOf(' ') >= 0) {
					codeStr = codeStr.replace('  ', '<br />');
					codeStr = codeStr.replace(' ', '<br />');
				}
				while(codeStr.indexOf('+') >= 0) {
					codeStr = codeStr.replace('++', '<br />');
					codeStr = codeStr.replace('+', '<br />');
				}
				while(codeStr.indexOf('&nbsp;') >= 0) {
					codeStr = codeStr.replace('&nbsp;&nbsp;', '<br />');
					codeStr = codeStr.replace('&nbsp;', '<br />');
				}
				var html = '<td class="td-code">' +
					'<div class="centerP"><div class="centerBody">' + codeStr +
					'</div></div></td>';
				trHtml += html;
			}
			trHtml += '</tr>';
			areaHtml += trHtml;
		}
		var codeArea = document.getElementById(idStr);
		codeArea.innerHTML = areaHtml;

		//添加点击方法 
		var tds = codeArea.querySelectorAll('.td-code');
		for(var i = 0; i < tds.length; i++) {
			var oneTd = tds[i];
			oneTd.id = idStr + '-' + i;
			oneTd.addEventListener('tap', selSchAbsCodeBtn);
		}
	}

	function selSchAbsCodeBtn() {
		var textareaE = document.getElementById('textarea');
		textareaE.blur();
		var popo = document.getElementById('selCodePopo');
		var oldActive = popo.querySelector('.dhc-active');
		if(oldActive && oldActive.id != this.id) {
			oldActive.classList.remove('dhc-active');
		}
		this.classList.add('dhc-active');

		var idArr = this.id.split('-');
		var typeStr = idArr[0];
		var index = parseInt(idArr[1]);
		var str, rw, type;
		if(typeStr == 'schArea') {
			var oneDict = schArr[index];
			str = oneDict['PostDesc'];
			rw = oneDict['PostID'];
			type = 'C'
		} else {
			var oneDict = absArr[index];
			str = oneDict['HolidayDesc'];
			rw = oneDict['rw'];
			type = 'H'
		}
		var schCode = document.getElementById('schCode');
		schCode.innerHTML = str;
		schCode.setAttribute('data-rw', rw);
		schCode.setAttribute('data-type', type);
		mui('#selCodePopo').popover('toggle');
	}

	function submitBtnClicked() {
		var dateE = document.getElementById('date');
		var dateStr = dateE.innerText;
		if(dateStr == '请选择') {
			mui.toast('请选择心愿班日期');
			return;
		}

		var schCodeE = document.getElementById('schCode');
		var schCodeStr = schCodeE.innerText;
		if(schCodeStr == '请选择') {
			mui.toast('请选择班种');
			return;
		}
		var rw = schCodeE.getAttribute('data-rw');
		var type = schCodeE.getAttribute('data-type');
		var textareaE = document.getElementById('textarea');
		var applyReason = textareaE.value;
		if(applyReason == '') {
			mui.toast('请填写申请理由');
			return
		}
		plus.nativeUI.showWaiting("正在提交", {
			modal: false
		});
		var PerId = getLocalData('pinfo').rw;
		var xmlStr = '<Request>^' + locId + '^' + PerId + '^' + dateStr + '^' +
			rw + '^' + type + '^' + applyReason + '</Request>';
		postHttpRequest(xmlStr, 'nurse.schedule.nurexpectsave', function(result) {
			plus.nativeUI.closeWaiting();
			var resultDict = eval('(' + result + ')');
			if(resultDict['success'] == true) {
				plus.storage.setItem('detail', '1');
				mui.toast('提交成功');
				mui.back();
			} else if(resultDict['msg'] != null || resultDict['msg'] != '') {
				mui.toast(resultDict['msg']);
			} else {
				mui.toast('提交失败,请重试');
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}

	/*提交
	 * rw^DepId(请假时护士所在病区)^PerId(护士人员Id)^ExpectDate(心愿班日期)^ExpectPostId(心愿班班次)^ExpectType(心愿班类型 值班C、休假H)
	 * 
	 * 入参说明 
	 */

})(mui);